package org.ibase4j.jwt.security;

import io.jsonwebtoken.ExpiredJwtException;
import org.ibase4j.jwt.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.ibase4j.core.util.WebUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final UserDetailsService userDetailsService;
    private final JwtTokenUtil jwtTokenUtil;
    private final String tokenHeader;

    public JwtAuthorizationTokenFilter(@Qualifier("jwtUserDetailsService") UserDetailsService userDetailsService, JwtTokenUtil jwtTokenUtil, @Value("${jwt.header}") String tokenHeader) {
        this.userDetailsService = userDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.tokenHeader = tokenHeader;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        logger.debug("processing authentication for '{}'", request.getRequestURL());
        WebUtil.REQUEST.set(request);

//        final String requestHeader = request.getHeader(this.tokenHeader);
//        String username = null;
//        String authToken = null;
//        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
//            authToken = requestHeader.substring(7);
//            try {
//                username = jwtTokenUtil.getUsernameFromToken(authToken);
//            } catch (ExpiredJwtException authException) {
//                logger.error("JWT授权令牌过期错误==>"+authException.getMessage());
//                WebUtil.writeCrosError(request,response,HttpServletResponse.SC_UNAUTHORIZED, "Token失效,请重新登录");
//                return;
//            }
//        }
//
//        logger.debug("checking authentication for user '{}'", username);
//
//        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
//            logger.debug("security context was null, so authorizating user");
//
//            // It is not compelling necessary to load the use details from the database. You could also store the information
//            // in the token and read it from it. It's up to you ;)
//            //从缓存中读取用户
//            JwtUser userDetails = this.jwtTokenUtil.getJwtUserFromCache();
//            if(userDetails == null){
//                logger.error("JWT授权令牌，缓存中不存在这个用户了==>"+userDetails);
//                WebUtil.writeCrosError(request,response,HttpServletResponse.SC_UNAUTHORIZED, "Token失效,请重新登录2");
//                return;
//            }
////            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
//            // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
//            // the database compellingly. Again it's up to you ;)
//            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
//                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
//                logger.info("登录已经授权的用户 '{}', 设置 security context", userDetails.getUsername());
//                SecurityContextHolder.getContext().setAuthentication(authentication);
//                WebUtil.saveCurrentUser(request, userDetails.change());
//            }
//        }
        chain.doFilter(request, response);
    }
}
